package com.yfjin.cut;

import android.media.AudioFormat;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

class MusicProgress {


    public void clip(String musicPath, String outPath, int startTime, int endTime) throws Exception {
        if (endTime < startTime) {
            return;
        }
        MediaExtractor mediaExtractor = new MediaExtractor();
        mediaExtractor.setDataSource(musicPath);
        int audioTrackIndex=selectTrack(mediaExtractor);
        mediaExtractor.selectTrack(audioTrackIndex);
        mediaExtractor.seekTo(startTime,MediaExtractor.SEEK_TO_CLOSEST_SYNC);


        MediaFormat mediaFormat=mediaExtractor.getTrackFormat(audioTrackIndex);

        int maxBufferSize=100*1000;
        if (mediaFormat.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)){
            maxBufferSize=mediaFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
        }


        ByteBuffer buffer=ByteBuffer.allocate(maxBufferSize);


        //"audio/aac" "audio/mmpg"
        MediaCodec mediaCodec=MediaCodec.createDecoderByType(mediaFormat.getString(MediaFormat.KEY_MIME));
        mediaCodec.configure(mediaFormat,null,null,0);



        File pcmFile = new File(outPath+"/out.pcm");
        FileChannel writeChannel = new FileOutputStream(pcmFile).getChannel();

        mediaCodec.start();
        MediaCodec.BufferInfo info=new MediaCodec.BufferInfo();
        int outputBufferIndex = -1;

        int count=0;
        while (true){

            count++;
            Log.i("123123","aa count:"+count);

            int decodeInputIndex=mediaCodec.dequeueInputBuffer(100*1000);

            if (decodeInputIndex>=0){

                long sampleTimeUs=mediaExtractor.getSampleTime();

                if (sampleTimeUs==-1){
                    break;
                }else if(sampleTimeUs<startTime){
                    //丢掉 不用了
                    mediaExtractor.advance();
                    continue;
                }else if(sampleTimeUs> endTime){
                    break;
                }


                info.size=mediaExtractor.readSampleData(buffer,0);
                info.presentationTimeUs=sampleTimeUs;
                info.flags=mediaExtractor.getSampleFlags();

                byte[] content=new byte[buffer.remaining()];
                buffer.get(content);


                FileUtils.writeContent(content);



                ByteBuffer inputBuffer=mediaCodec.getInputBuffer(decodeInputIndex);
                inputBuffer.put(content);
                mediaCodec.queueInputBuffer(decodeInputIndex,0,info.size,info.presentationTimeUs,info.flags);
                mediaExtractor.advance();

            }


            outputBufferIndex = mediaCodec.dequeueOutputBuffer(info, 100_000);
            while (outputBufferIndex>=0) {

                Log.i("123123","bb count:"+count);

                ByteBuffer decodeOutputBuffer = mediaCodec.getOutputBuffer(outputBufferIndex);
                writeChannel.write(decodeOutputBuffer);//MP3  1   pcm2
                mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
                outputBufferIndex = mediaCodec.dequeueOutputBuffer(info, 100_000);
            }

        }



        writeChannel.close();
        mediaExtractor.release();
        mediaCodec.stop();
        mediaCodec.release();


        File file=new File(outPath,"out.wav");
        new PcmToWavUtil(44100,  AudioFormat.CHANNEL_IN_STEREO,
                2, AudioFormat.ENCODING_PCM_16BIT)
                .pcmToWav(pcmFile.getAbsolutePath(),file.getAbsolutePath());


        Log.i("123123", "mixAudioTrack: 转换完毕");
    }


    private int selectTrack(MediaExtractor mediaExtractor) {
        //获取每条轨道
        int numTracks = mediaExtractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = mediaExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("audio/")) {
                return i;
            }
        }
        return -1;
    }
}
